#include "timer_util.h"
#include <string.h>

#define MAX_TIMER_NUM         20


typedef struct{
	uint16_t id;
	uint16_t state;
	uint32_t span;
	cbTimerEvent cb;
}Item;



static Item  Timeres[MAX_TIMER_NUM] = {0};


static Item* AllocItem()
{
	int i;

	
	for(i=0; i < MAX_TIMER_NUM; i++){
		if(Timeres[i].id  ==  0){
			return &Timeres[i];
		}
	}
	
	return 0;
}



bool CreateTimer(uint16_t id, uint32_t span, cbTimerEvent cb)
{
	Item* pNewItem;

	int i;
	for(i=0; i < MAX_TIMER_NUM; i++){
		if(Timeres[i].id  ==  id){
			Timeres[i].span  = span;
			Timeres[i].state  = 1;
			Timeres[i].cb    = cb;
			return true;
		}
	}
	
	
    pNewItem  = AllocItem();
	
	if(pNewItem){
		pNewItem->id  = id;
		pNewItem->span = span;
		pNewItem->state  = 1;
		pNewItem->cb  = cb;
		
		return true;
	}
	else{
		return false;
	}
}



void RestartTimer(uint16_t id, uint32_t span)
{
	int i;
	for(i = 0; i < MAX_TIMER_NUM; i++){
		if(Timeres[i].id  == id){
			Timeres[i].span  = span;
			Timeres[i].state  = 1;			
		}
	}
}



void DestroyTimer(uint16_t id)
{
	int i;
	for(i = 0; i < MAX_TIMER_NUM; i++){
		if(Timeres[i].id == id){
			memset(&Timeres[i], 0, sizeof(Timeres[0]));
			return;
		}
	}
}



void OnTimerTick(void)
{
	int i;
	for(i = 0; i < MAX_TIMER_NUM; i++){
		if(Timeres[i].id  &&  Timeres[i].state){
			Timeres[i].span--;
			if(Timeres[i].span == 0){
				Timeres[i].state  = 0;
				Timeres[i].cb(Timeres[i].id);
			}
		}
	}
}





